'use client'

import {createEditor, $getRoot, $getSelection, $createParagraphNode, $createTextNode} from 'lexical';
import { useEffect } from "react"

let editor: any = null;
export default function Lexicalpage() {
    useEffect(() => {
        const config = {
            namespace: 'MyEditor',
            theme: {
            },
        };
    
        editor = createEditor(config);
        const contentEditableElement = window.document.getElementById('editor');
    
        editor.setRootElement(contentEditableElement);

        const stringifiedEditorState = JSON.stringify(editor.getEditorState().toJSON());

        const newEditorState = editor.parseEditorState(stringifiedEditorState);
        
        // editor.setEditable(true)
        console.log('editor', newEditorState);
        
    }, [])

    const handleClick = () => {
        console.log('click', editor);
        if (!editor) return
        editor.update(() => {
            // Get the RootNode from the EditorState
            const root = $getRoot();
            console.log('root', root);
          
            // Get the selection from the EditorState
            const selection = $getSelection();
          
            // Create a new ParagraphNode
            const paragraphNode = $createParagraphNode();
          
            // Create a new TextNode
            const textNode = $createTextNode('Hello world');
          
            // Append the text node to the paragraph
            paragraphNode.append(textNode);
          
            // Finally, append the paragraph to the root
            root.append(paragraphNode);
          });
    }

    return <div>
            <div onClick={handleClick}>Update</div>
            <div id="editor" style={{width: 400, height: 400, backgroundColor: 'pink'}}>This is a lexical page</div>
        </div>
}